<template>
  <view class="search-container">
    <!-- 搜索栏 -->
    <view class="search-header">
      <uni-search-bar 
        v-model="searchKeyword"
        @input="onSearchInput"
        @confirm="handleSearch"
        placeholder="搜索菜品或食材"
        :focus="true"
        :show-action="true"
        action-text="搜索"
        @action="handleSearch"
      />
    </view>

    <!-- 热门搜索 -->
    <view class="hot-search" v-if="!searchKeyword && hotSearchList.length > 0">
      <view class="section-title">热门搜索</view>
      <view class="tag-list">
        <text 
          class="search-tag" 
          v-for="tag in hotSearchList" 
          :key="tag"
          @click="searchByTag(tag)"
        >
          {{ tag }}
        </text>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="search-history" v-if="!searchKeyword && searchHistory.length > 0">
      <view class="section-title">
        最近搜索
        <text class="clear-history" @click="clearHistory">清空</text>
      </view>
      <view class="history-list">
        <view 
          class="history-item" 
          v-for="item in searchHistory" 
          :key="item"
          @click="searchByTag(item)"
        >
          <uni-icons type="clock" size="16" color="#999" />
          <text class="history-text">{{ item }}</text>
        </view>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-results" v-if="searchKeyword">
      <view class="result-header">
        <text class="result-count">找到 {{ searchResults.length }} 个结果</text>
      </view>
      
      <view v-if="searchResults.length === 0 && !searching" class="empty-result">
        <uni-icons type="search" size="60" color="#ccc" />
        <text class="empty-text">暂无相关菜品</text>
      </view>
      
      <view class="result-list" v-else>
        <view 
          class="result-item" 
          v-for="dish in searchResults" 
          :key="dish.id"
          @click="viewDishDetail(dish.id)"
        >
          <image :src="dish.image" class="result-image" mode="aspectFill" />
          <view class="result-info">
            <text class="result-name">{{ dish.name }}</text>
            <text class="result-desc">{{ dish.description }}</text>
            <view class="result-meta">
              <uni-rate :value="dish.rating" :readonly="true" :size="12" />
              <text class="rating-text">{{ dish.rating }}</text>
              <text class="ingredients-text">主料: {{ dish.mainIngredients }}</text>
            </view>
          </view>
          <view class="result-actions">
            <button 
              class="action-btn" 
              @click.stop="toggleFavorite(dish)"
              :class="{ 'favorited': dish.isFavorited }"
            >
              {{ dish.isFavorited ? '已收藏' : '收藏' }}
            </button>
          </view>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <uni-load-more :status="loadStatus" v-if="searching || searchResults.length > 0" />
    </view>
  </view>
</template>

<script>
import { searchDish, toggleFavorite } from '@/api/diet'

export default {
  data() {
    return {
      searchKeyword: '',
      searchResults: [],
      hotSearchList: ['家常菜', '牛肉', '鸡蛋汤', '减肥餐', '素食', '川菜', '粤菜', '营养汤'],
      searchHistory: [],
      searching: false,
      loadStatus: 'more',
      searchTimer: null
    }
  },
  onLoad() {
    this.loadSearchHistory()
  },
  methods: {
    loadSearchHistory() {
      this.searchHistory = uni.getStorageSync('searchHistory') || []
    },
    
    saveSearchHistory(keyword) {
      if (!keyword.trim()) return
      
      let history = uni.getStorageSync('searchHistory') || []
      // 移除重复项
      history = history.filter(item => item !== keyword)
      // 添加到开头
      history.unshift(keyword)
      // 限制历史记录数量
      if (history.length > 10) {
        history = history.slice(0, 10)
      }
      
      uni.setStorageSync('searchHistory', history)
      this.searchHistory = history
    },
    
    clearHistory() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('searchHistory')
            this.searchHistory = []
          }
        }
      })
    },
    
    onSearchInput(value) {
      // 防抖搜索
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      
      if (value.trim()) {
        this.searchTimer = setTimeout(() => {
          this.performSearch(value)
        }, 500)
      } else {
        this.searchResults = []
      }
    },
    
    handleSearch() {
      if (this.searchKeyword.trim()) {
        this.performSearch(this.searchKeyword)
        this.saveSearchHistory(this.searchKeyword)
      }
    },
    
    searchByTag(tag) {
      this.searchKeyword = tag
      this.performSearch(tag)
      this.saveSearchHistory(tag)
    },
    
    async performSearch(keyword) {
      if (!keyword.trim()) return
      
      try {
        this.searching = true
        this.loadStatus = 'loading'
        
        const res = await searchDish({
          keyword: keyword.trim(),
          pageNum: 1,
          pageSize: 20
        })
        
        this.searchResults = res.rows || []
        this.loadStatus = 'noMore'
      } catch (error) {
        this.$modal.msgError('搜索失败')
        this.loadStatus = 'more'
      } finally {
        this.searching = false
      }
    },
    
    viewDishDetail(dishId) {
      uni.navigateTo({
        url: `/pages/diet/detail/index?id=${dishId}`
      })
    },
    
    async toggleFavorite(dish) {
      try {
        await toggleFavorite(dish.id)
        dish.isFavorited = !dish.isFavorited
        this.$modal.msgSuccess(dish.isFavorited ? '收藏成功' : '取消收藏')
      } catch (error) {
        this.$modal.msgError('操作失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.search-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-header {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin: 30rpx 20rpx 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.clear-history {
  font-size: 24rpx;
  color: #999;
  font-weight: normal;
}

.tag-list {
  padding: 0 20rpx;
  display: flex;
  flex-wrap: wrap;
}

.search-tag {
  display: inline-block;
  background: white;
  color: #666;
  font-size: 26rpx;
  padding: 15rpx 25rpx;
  border-radius: 30rpx;
  margin: 0 15rpx 15rpx 0;
  border: 1rpx solid #e8e8e8;
}

.history-list {
  background: white;
  margin: 0 20rpx;
  border-radius: 16rpx;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 25rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.history-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 20rpx;
}

.result-header {
  padding: 20rpx;
}

.result-count {
  font-size: 26rpx;
  color: #666;
}

.empty-result {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-text {
  display: block;
  margin-top: 20rpx;
  font-size: 28rpx;
}

.result-list {
  padding: 0 20rpx;
}

.result-item {
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}

.result-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.result-info {
  flex: 1;
}

.result-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.result-desc {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.result-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.rating-text {
  font-size: 22rpx;
  color: #666;
  margin-left: 10rpx;
  margin-right: 20rpx;
}

.ingredients-text {
  font-size: 22rpx;
  color: #999;
}

.result-actions {
  margin-left: 20rpx;
}

.action-btn {
  background: white;
  color: #666;
  border: 1rpx solid #ddd;
  border-radius: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  
  &.favorited {
    background: #ff4d4f;
    color: white;
    border-color: #ff4d4f;
  }
}
</style>